<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="cpItemList"
      />
    </div>
    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <!-- 验收信息-->
      <customForm :data="form" :rules="propRules" ref="editFormCheck" :disabled="cpDisabledEditFormCheck"  v-show="cpIsMenuCheck">
        <template #content>
          <div id="box-info-accept" class="box-title">验收信息</div>
          <customFormItem label="验收通过" name="repairAcceptResult" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
          />
          <customFormItem label="验收人" name="repairAcceptUser" :parent="_self" :form="form"/>
          <customFormItem
            label="验收相关附件"
            name="workFileRepair"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            width2x
          >
            <template #content>
              <customUpload
                :data="{ fileRefId: form.id + 'check', fileRefTable: 'device_work', fileSavePath: 'device_work'}"
                :hide="propParent.cpFormNew"
                hideMsg="请先保存主单据后再上传"
                :max="20"
                :disabled="cpDisabledEditFormCheck"
                multiple
              />
            </template>
          </customFormItem>
        </template>
      </customForm>

      <!-- 维修信息-->
      <customForm :data="form" :rules="propRules" ref="editFormHandle" :disabled="cpDisabledEditFormHandle"  v-show="cpIsMenuHandle || cpIsMenuCheck">
        <template #content>
          <div id="box-info-handle" class="box-title">维修信息</div>
          <customFormItem
            label="维修完成时间" name="repairTimeEnd" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            :config="{'enable-time-picker': true}"
            width2x
          />

          <customFormItem label="维修结果" name="repairResult" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.deviceRepairResult}"
          />
          <customFormItem label="维修人" name="repairUser" :parent="_self" :form="form"/>
          <customFormItem label="停机时长(小时)" name="repairDownHour" :parent="_self" :form="form" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="维修工时(小时)" name="repairUseHour" :parent="_self" :form="form" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="维修总费用" name="repairAmountAll" :parent="_self" :form="form" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="配件总费用" name="repairPartAll" :parent="_self" :form="form" :type="constCommon.formItemType.inputNumber.name"/>

          <customFormItem
            label="维修相关附件"
            name="workFileRepair"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            width2x
          >
            <template #content>
              <customUpload
                :data="{ fileRefId: form.id + 'repair', fileRefTable: 'device_work', fileSavePath: 'device_work'}"
                :hide="propParent.cpFormNew"
                hideMsg="请先保存主单据后再上传"
                :max="20"
                :disabled="cpDisabledEditFormHandle"
                multiple
              />
            </template>
          </customFormItem>
        </template>
      </customForm>

      <div id="box-part-handle" class="box-title"   v-show="cpIsMenuHandle || cpIsMenuCheck">维修配件清单</div>
      <data-view ref= "childDataViewPart"
                 :propHideFlowSelect = "true"
                 propViewKey="device_part"
                 :propAutoFetchData="false"
                 class="data-view-inlinebtn"
                 :propIsTdesign="true"
                 :propOnlyQueryAll="cpDisabledEditFormHandle"
                 @edit-input="partRowEditInput"
                 v-show="cpIsMenuHandle || cpIsMenuCheck"
      />

      <!-- 派单信息-->
      <customForm :data="form" :rules="propRules" ref="editFormDispatch" :disabled="cpDisabledEditFormDispatch" v-show="cpIsMenuDispatch || cpIsMenuHandle || cpIsMenuCheck">
        <template #content>
          <div id="box-info-dispatch" class="box-title">派单信息</div>
          <customFormItem
            label="派单给"
            name="dispatchUserNames"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="$refs.treeUserDrawer.show([],dispatchUserNamesSelect)"
            fullWidth
          />
          <customFormItem
            label="接受人"
            name="dispatchUserNameAccept"
            :parent="_self"
            :form="form"
            disabled
          />

          <customFormItem
            label="派单相关附件"
            name="workFileDispatch"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            width2x
          >
            <template #content>
              <customUpload
                :data="{ fileRefId: form.id + 'Dispatch', fileRefTable: 'device_work', fileSavePath: 'device_work'}"
                :hide="propParent.cpFormNew"
                hideMsg="请先保存主单据后再上传"
                :max="20"
                multiple
                :disabled="cpDisabledEditFormDispatch"
              />
            </template>
          </customFormItem>
        </template>
      </customForm>

      <!--报修信息-->
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly || !cpIsMenuAdd">
        <template #content>
          <div id="box-base" class="box-title">报修信息</div>
          <customFormItem label="报修名称" name="busTitle" :parent="_self" :form="form" />
          <customFormItem
            label="来源科室"
            name="deptNameFrom"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.dept(deptNameFromChange)"
            :disabled="!propParent.cpFormNew"
          />
          <customFormItem label="报修单号" name="busKey" :parent="_self" :form="form" disabled/>
          <customFormItem label="报修日期" name="busDate" :parent="_self" :form="form"
                          :type="constCommon.formItemType.datePicker.name"  disabled/>
          <customFormItem label="报修人" name="busUser" :parent="_self" :form="form"  disabled/>
          <customFormItem label="报修人电话" name="applyPhone" :parent="_self" :form="form"  />

          <customFormItem label="故障类型" name="faultType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.deviceFaultType}"
          />
          <customFormItem label="紧急程度" name="needLevel" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.needLevel}"
          />
          <customFormItem label="故障等级" name="faultLevel" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.faultLevel}"
          />
          <customFormItem label="要求完成时间" name="needDate" :parent="_self" :form="form" :type="constCommon.formItemType.datePicker.name"/>
          <customFormItem label="备注" name="remark" :parent="_self" :form="form"/>
          <customFormItem
            label="报修相关附件"
            name="workFile"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            width2x
          >
            <template #content>
              <customUpload
                :data="{ fileRefId: form.id, fileRefTable: 'device_work', fileSavePath: 'device_work'}"
                :hide="propParent.cpFormNew"
                hideMsg="请先保存主单据后再上传"
                :max="20"
                :disabled="propReadonly || !cpIsMenuAdd"
                multiple
              />
            </template>
          </customFormItem>
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">报修详情</div>
      <customTooltip title="title" v-show="!propReadonly && cpIsMenuAdd && !propParent.cpFormNew">
        <template #title>
          选择设备或者扫描设备标签码
        </template>
        <template #content>
          <FortenScan ref="scan" propPlaceholder="请扫描" style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px" @after-scan="barCodeScan" propType="uniqueCode"/>
          <customButton title="选择设备" theme="primary" @click="deviceMore" style="height: 35px;line-height: 35px;"/>
        </template>
      </customTooltip>
      <data-view ref= "childDataView"
                 :propHideFlowSelect = "true"
                 propViewKey="device_work_item_repair"
                 :propFlowKey="propParent.propFlowKey"
                 :propInitData="form"
                 :propParentPage="_self"
                 :propParentData="propParent.viewFormData"
                 :propAutoFetchData="false"
                 :propsDisableDbClick="true"
                 :propTableHide="propParent.cpFormNew"
                 propTableHideMsg="请先保存主单据"
                 class="data-view-inlinebtn"
                 @afterTableDataChange="afterTableDataChange"
      />
    </div>

    <treeUserDrawer ref="treeUserDrawer"/>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import customUpload from "@/components/custom/form/customUpload.vue";
import treeUserDrawer from "@/components/custom/bus/treeUserDrawer.vue";

export default {
  desc: '设备工作表-报修、派单、维修、验收',
  data() {
    return {
      form: {},
    }
  },
  computed: {
    // 导航列表
    cpItemList() {
      let itemList = [
        { name: 'box-base', title: `报修信息` },
        { name: 'box-dtl', title: `报修详情` },
      ]
      if (this.cpIsMenuDispatch) { // 派单菜单进入
        itemList.unshift({ name: 'box-info-dispatch', title: `派单信息` })
      } else if (this.cpIsMenuHandle) { // 维修菜单进入
        itemList.unshift({ name: 'box-info-dispatch', title: `派单信息` })
        itemList.unshift({ name: 'box-part-handle', title: `维修配件清单` })
        itemList.unshift({ name: 'box-info-handle', title: `维修信息` })
      } else if (this.cpIsMenuCheck) { // 验收菜单进入
        itemList.unshift({ name: 'box-info-dispatch', title: `派单信息` })
        itemList.unshift({ name: 'box-part-handle', title: `维修配件清单` })
        itemList.unshift({ name: 'box-info-handle', title: `维修信息` })
        itemList.unshift({ name: 'box-info-accept', title: `验收信息` })
      }
      return itemList
    },
    // 菜单类型
    cpMenuType() {
      return this.propInitData && this.propInitData.menuType ? this.propInitData.menuType : '-1'
    },
    // 是否报修菜单进入
    cpIsMenuAdd() {
      return  this.cpMenuType == 'add'
    },
    // 是否派单菜单进入
    cpIsMenuDispatch() {
      return  this.cpMenuType == 'dispatch'
    },
    // 是否维修菜单进入
    cpIsMenuHandle() {
      return  this.cpMenuType == 'handle'
    },
    // 是否验收菜单进入
    cpIsMenuCheck() {
      return  this.cpMenuType == 'check'
    },
    // 表单标识
    cpFormRef() {
      if (this.cpIsMenuAdd) {
        return 'editForm'
      }
      if (this.cpIsMenuDispatch) {
        return 'editFormDispatch'
      }
      if (this.cpIsMenuHandle) {
        return 'editFormHandle'
      }
      if (this.cpIsMenuCheck) {
        return 'editFormCheck'
      }
    },
    // 验收表单是否禁用
    cpDisabledEditFormCheck() {
      return !['checking'].includes(this.form.flowStatus)
    },
    // 维修表单是否禁用
    cpDisabledEditFormHandle() {
      return !['repairing'].includes(this.form.flowStatus)
    },
    // 派单表单是否禁用
    cpDisabledEditFormDispatch() {
      return !['dispatching'].includes(this.form.flowStatus)
    },
  },
  created() {
    let that = this
    this.$emit('event-register', {
      //表单校验
      validate: (callback) => {
        return that.$refs[that.cpFormRef].validate(callback)
      },

      //保存前操作
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },

      //数据加载后
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (this.propParent.cpFormNew) {
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'deptIdFrom', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptNameFrom', this.utils.getCurrentUser().deptName)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'busType', this.constCommon.dictType.deviceBusTypeRepair)
          this.$set(this.form, 'busKey', '自动获取')
        }
        this.loadDtl()
        this.loadDtlPart()
      },

      //数据保存后
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },

      //数据删除后
      afterDelete: () => {
      },

      //流程提交前
      beforeFlow: (code, button) => {
        return true
      },

      //流程提交后
      afterFlow: (flowButtonKey) => {
      },

      //表单关闭前
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    //上级对象
    propParent: Object,
    //上级初始化数据
    propInitData: Object,
    //主键字段
    propPrimaryKey: String,
    //数据字典
    propDictionaries: Object,
    //当前操作行
    propCurrentRow: Object,
    //表单数据
    propViewFormData: Object,
    //是否只读
    propReadonly: Boolean,
    //操作状态
    propStatus: String,
    //表单规则
    propRules: Object,
    propParam: Object,
  },
  components: {
    customUpload,
    customAnchor,
    treeUserDrawer
  },
  methods: {
    //扫码SN或RFID
    barCodeScan(txtScan) {
      this.utilVue.loadShow(true)
      this.$ajax.post('/device/work_item/addByScan?txtScan', {'workId': this.form.id, 'deviceSn': txtScan}).then(
        resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.loadDtl()
          }
          this.utilVue.loadHide()
        }
      )
    },

    // 加载明细
    loadDtl() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('workId', this.form.id)
      } else {
        queryWrapper.eq('workId', -1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },

    // 加载配件明细
    loadDtlPart() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('workId', this.form.id)
      } else {
        queryWrapper.eq('workId', -1)
      }
      this.$refs.childDataViewPart.setQueryWrapper(queryWrapper)
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },
    // 来源科室选择
    deptNameFromChange(item) {
      this.$set(this.form, 'deptIdFrom', item.id)
      this.$set(this.form, 'deptNameFrom', item.name)
    },
    // 设备选择
    deviceSelect(rows) {
      //转换属性
      rows.forEach(ob => {
        ob.ledgerId = ob.id
        ob.workId = this.form.id
      })

      //批量添加
      this.utilVue.loadShow(true)
      this.$ajax.post('/device/work_item/saveBatch', rows).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
        }
      })
    },

    // 选择设备
    deviceMore() {
      this.utilSelect.deviceMore(this.deviceSelect, this.form.deptIdFrom)
    },

    // 派单人选择
    dispatchUserNamesSelect(rows) {
      this.$set(this.form, 'dispatchUserNames', rows.map(item => item.name).join(','))
      this.$set(this.form, 'dispatchUserIds', rows.map(item => item.id).join(','))
    },

    partRowEditInput({row, column}) {
      this.$set(row, 'workId', this.form.id)
    }
  }
}
</script>
